/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
<template>
  <div class="user-info-model password-model">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="mini"
      label-position="left"
    >
      <el-form-item
        :label="$t('User Name')"
        label-width="80px"
      >
        <span class="sp1">{{userInfo.userName}}</span>
      </el-form-item>
      <el-form-item
        :label="$t('Password')"
        label-width="80px"
        prop="userPassword"
      >
        <el-input
          style="width: 320px;"
          type="password"
          size="small"
          v-model="form.userPassword"
          :placeholder="$t('Please enter your password')"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('Confirm Password')"
        label-width="80px"
        prop="oldUserPassword"
      >
        <el-input
          style="width: 320px;"
          type="password"
          size="small"
          v-model="form.oldUserPassword"
          :placeholder="$t('Please enter confirm password')"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label=""
        label-width="80px"
      >
        <el-button
          type="primary"
          size="small"
          @click="_edit()"
          :loading="spinnerLoading"
        >{{spinnerLoading ? $t('Loading...') : $t('Edit')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import i18n from '@/module/i18n'
  import { mapState, mapActions } from 'vuex'
  // import mListBoxF from '@/module/components/listBoxF/listBoxF'

  export default {
    name: 'password-info',
    data () {
      /* validatepass */
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.form.userPassword !== '') {
            let regPassword = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]+$)[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,22}$/
            // password
            if (!regPassword.test(value)) {
              return callback(new Error(`${i18n.$t('Password consists of at least two combinations of numbers, letters, and characters, and the length is between 6-22')}`))
            }
          }
          callback()
        }
      }
      /* validatePassAgain */
      const validatePassAgain = (rule, value, callback) => {
        if (value === '请再次输入密码') {
          callback(new Error())
        } else {
          if (this.form.userPassword !== value) {
            return callback(new Error(`${i18n.$t('The password is inconsistent with the confirmation password')}`))
          }
          callback()
        }
      }
      return {
        // loading
        spinnerLoading: false,
        form: {
          // user password
          userPassword: '',
          // Confirm password
          oldUserPassword: '',
        },
        rules: {
          userPassword: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur' },
          ],
          oldUserPassword: [
            { required: true, message: '请输入确定密码', trigger: 'blur' },
            { validator: validatePassAgain, trigger: 'blur' },
          ],
        }
      }
    },
    props: {},
    methods: {
      ...mapActions('user', ['signOut']),
      ...mapActions('security', ['updateUser']),
      /**
       * edit
       */
      _edit () {
        this.$refs.form.validate(valid => {
          if (!valid) return
          let param = {
            id: this.userInfo.id,
            userName: this.userInfo.userName,
            userPassword: this.form.userPassword,
            tenantId: this.userInfo.tenantId,
            roleId: this.userInfo.roleId,
            email: this.userInfo.email,
            phone: this.userInfo.phone,
            state: this.userInfo.state
          }
          this.spinnerLoading = true
          this.updateUser(param).then(res => {
            this.$message.success(res.msg)
            setTimeout(() => {
              this.spinnerLoading = false
              this.signOut()
            }, 1500)
          }).catch(e => {
            this.$message.error(e.msg || '')
            this.spinnerLoading = false
          })
        })
        // verification
        // if (this._verification()) {
        //   let param = {
        //     id: this.userInfo.id,
        //     userName: this.userInfo.userName,
        //     userPassword: this.userPassword,
        //     tenantId: this.userInfo.tenantId,
        //     roleId: this.userInfo.roleId,
        //     email: this.userInfo.email,
        //     phone: this.userInfo.phone,
        //     state: this.userInfo.state
        //   }
        //   this.spinnerLoading = true
        //   this.updateUser(param).then(res => {
        //     this.$message.success(res.msg)
        //     setTimeout(() => {
        //       this.spinnerLoading = false
        //       this.signOut()
        //     }, 1500)
        //   }).catch(e => {
        //     this.$message.error(e.msg || '')
        //     this.spinnerLoading = false
        //   })
        // }
      },
      /**
       * verification
       */
      // _verification () {
      //   let regPassword = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]+$)[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,22}$/

      //   // password
      //   if (!regPassword.test(this.userPassword)) {
      //     this.$message.warning(`${i18n.$t('Password consists of at least two combinations of numbers, letters, and characters, and the length is between 6-22')}`)
      //     return false
      //   }

      //   // confirm password
      //   if (this.userPassword !== this.oldUserPassword) {
      //     this.$message.warning(`${i18n.$t('The password is inconsistent with the confirmation password')}`)
      //     return false
      //   }
      //   return true
      // }
    },
    computed: {
      ...mapState('user', ['userInfo'])
    },
    // components: { mListBoxF }
  }
</script>

<style lang="scss" rel="stylesheet/scss">
.user-info-model {
  padding: 20px;
  padding-bottom: 0;
}
.password-model {
  .list-box-f {
    margin-bottom: 20px;
    .sp1 {
      font-size: 14px;
      color: #333;
      display: inline-block;
      padding-top: 6px;
    }
  }
}
</style>
